/**
* Created with CLion.
* User:Lenovo
* Date:2023-04-14
* Time:14:26
* Description:顺序表
*/

#include "SeqList.h"

void SLInit(SL *psl)
{
    assert(psl);
    psl -> a = (SLDataType *)malloc(sizeof(SLDataType) * 4);
    if (psl -> a == NULL)
    {
        perror("malloc fail");
        return;
    }
    psl -> capacity = 4;
    psl -> size = 0;
}

void SLDestroy(SL *psl)
{
    assert(psl);
    free(psl -> a);
    psl -> a = NULL;
    psl -> size = 0;
    psl -> capacity = 0;
}

void SLCheckCapacity(SL *psl)
{
    assert(psl);
    if (psl -> size == psl -> capacity)
    {
        SLDataType *tmp = realloc(psl -> a, sizeof(SLDataType) * psl -> capacity * 2);
        if (tmp == NULL)
        {
            perror("realloc fail");
            return;
        }
        psl -> a = tmp;
        psl -> capacity *= 2;
    }
}

void SLPushBack(SL *psl, SLDataType x)
{
    assert(psl);
    // SLCheckCapacity(psl);

    // psl -> a[psl -> size] = x;
    // psl -> size++;
    SLInsert(psl, x, psl -> size);
}

void SLPushFront(SL *psl, SLDataType x)
{
    assert(psl);
    // SLCheckCapacity(psl);
    // //挪动数据：从后往前挪
    // int end = psl -> size - 1;
    // while (end >= 0)
    // {
    //     psl -> a[end + 1] = psl -> a[end];
    //     end--;
    // }

    // psl -> a[0] = x;
    // psl -> size++;

    SLInsert(psl, x, 0);
}

void SLPopBack(SL *psl)
{
    assert(psl);
    // //为空 -> ?
    // // 1.暴力检查
    // assert(psl -> size > 0);

    // // 2.温柔的检查
    // /*
    //  * if (psl -> size == 0)
    //  * {
    //  *     return;
    //  * }
    //  */

    // psl -> size--;
    // //不管尾部的数据

    SLErase(psl, psl -> size - 1);
}

void SLPopFront(SL *psl)
{
    assert(psl);
    // assert(psl -> size > 0);

    // //挪动数据：从前往后
    // int start = 0;
    // while (start < psl -> size - 1)
    // {
    //     psl -> a[start] = psl -> a[start + 1];
    //     start++;
    // }
    // psl -> size--;

    SLErase(psl, 0);
}

void SLInsert(SL *psl, SLDataType x, int pos)
{
    assert(psl);
    assert(pos >= 0 && pos <= psl -> size);
    SLCheckCapacity(psl);

    int end = psl -> size - 1;
    while (end >= pos)
    {
        psl -> a[end + 1] = psl -> a[end];
        end--;
    }

    psl -> a[pos] = x;
    psl -> size++;
}

void SLErase(SL *psl, int pos)
{
    assert(psl);
    assert(pos >= 0 && pos < psl -> size);

    int start = pos + 1;
    while (start < psl -> size)
    {
        psl -> a[start - 1] = psl -> a[start];
        start++;
    }
    psl -> size--;
}

int SLFind(SL *psl, SLDataType x)
{
    assert(psl);
    for (int i = 0; i < psl -> size; i++)
    {
        if (psl -> a[i] == x)
        {
            return i;
        }
    }

    return -1;
}

void SLModify(SL *psl, int pos, SLDataType x)
{
    assert(psl);
    assert(pos >= 0 && pos < psl -> size);
    psl -> a[pos] = x;
}

void SLPrint(SL *psl)
{
    assert(psl);
    for (int i = 0; i < psl -> size; i++)
    {
        printf("%d ", psl -> a[i]);
    }
    printf("\n");
}